const app = getApp()

import axios from '../../utils/axios'

Component({

  options: {
    styleIsolation: 'apply-shared',
    multipleSlots: true
  },

  /**
   * 组件的属性列表
   */
  properties: {
    couponList: Object
  },

  /**
   * 组件的初始数据
   */
  data: {
    eventInfo: null,
  },

  /**
   * 组件的方法列表
   */
  methods: {

    getUserInfo: function (e) {

      // 当接口返回‘请登录’时，showLogin就变为true，然后调用授权
      if (e.detail.userInfo && app.globalData.showLogin) {
        app.globalData.showLogin = false
        const self = this
        app.signin(e.detail, function (res) {

          axios('/groupon/coupons', {
            store_id: app.globalData.storeId
          }).then(res => {
            if (res.data.resultcode == 1) {

              let list = res.data.result.store
              let itemJson = []

              let notJson = []

              for (let i = 0; i < list.length; i++) {
                if (list[i].receive_status == 1) {
                  itemJson.push(list[i])
                } else {
                  notJson.push(list[i])
                }
              }

              let tempList = itemJson.concat(notJson)

              self.setData({
                couponList: tempList
              })

            }
          })

          self.getCoupon(self.data.eventInfo)
        })
      }

    },

    // 点击领取优惠券
    getCoupon: function (e) {
      let couponId = e.currentTarget.dataset.couponid

      this.setData({
        eventInfo: e
      })

      axios('/personal/drawCoupon', {
        coupon_id: couponId
      }).then(res => {
        console.log(res)
        if (res.data.resultcode == 1) {
          wx.showToast({
            title: '领取成功！',
            icon: 'none',
            duration: 1300
          })
          for (let i = 0; i < this.data.couponList.length; i++) {
            if (this.data.couponList[i].coupons_id == couponId) {
              this.data.couponList[i].receive_status = 0
              this.setData({
                couponList: this.data.couponList
              })
            }
          }
        } else {
          wx.showToast({
            title: res.data.message,
            icon: 'none',
            duration: 1300
          })
        }
      })

    },

  }

})